package com.project.common.core.utils;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;

public class AudioUtils {


    //获取音频时长
    public static int  AudioDuration(String FilePath) throws Exception{
        String  linuxorder="ffmpeg";
        String  param="-i";
        List<String> commands = new ArrayList<String>();
        commands.add(linuxorder);
        commands.add(param);
        commands.add(FilePath);
        String result=writeLinuxBash(commands);//获取音频信息
        String strtimelen=Reg.RegMatch(result,"Duration: (.*?),");
        int timelen=getTimelen(strtimelen);
        return timelen;
    }

    //格式:"00:00:10.68"
    private static int getTimelen(String timelen){
        if (timelen == null || timelen.equals("N/A")){
            return 1;
        }
        int min=0;
        String strs[] = timelen.split(":");
        if (strs[0].compareTo("0") > 0) {
                 min+=Integer.valueOf(strs[0])*60*60;//秒
        }
        if(strs[1].compareTo("0")>0){
               min+=Integer.valueOf(strs[1])*60;
        }
        if(strs[2].compareTo("0")>0){
                 min+=Math.round(Float.valueOf(strs[2]));
        }
        return min;
    }



    /**
     * linux bash 写入
     */

    public static String writeLinuxBash(List<String> commands) throws IOException{
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(commands);
        final Process p = builder.start();
        //从输入流中读取视频信息
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
         String line = "";
         String result="";
         while ((line = br.readLine()) != null) {
             result=result+line;
          }
        br.close();
        return result;
    }

}






